package com.test.mvn.sql_parser;

import java.util.List;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlExportParameterVisitor;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.visitor.ExportParameterVisitor;
import com.alibaba.druid.util.JdbcConstants;

/**
 * Hello world!
 *
 */
public class App {

	public static void main(String[] args) {
		String sql = "select * from t where id = 3 and name = 'abc'";

		List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);

		StringBuilder out = new StringBuilder();
		ExportParameterVisitor visitor = new MySqlExportParameterVisitor(out);
		for (SQLStatement stmt : stmtList) {
			stmt.accept(visitor);
		}

		String paramteredSql = out.toString();
		System.out.println(paramteredSql);

		List<Object> paramters = visitor.getParameters(); // [3, "abc"]
		for (Object param : paramters) {
			System.out.println(param);
		}
	}
	
	

	public static void main1(String[] args) {

		// String sql = "update t set name = 'x' where id < 100 limit 10";
		// String sql = "SELECT ID, NAME, AGE FROM USER WHERE ID = ? limit 2";
		// String sql = "select * from tablename limit 10";

		String sql = "select user from emp_table";
		String dbType = JdbcConstants.MYSQL;

		// 格式化输出
		String result = SQLUtils.format(sql, dbType);
		System.out.println(result); // 缺省大写格式
		List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);

		// 解析出的独立语句的个数
		System.out.println("size is:" + stmtList.size());
		for (int i = 0; i < stmtList.size(); i++) {

			SQLStatement stmt = stmtList.get(i);
			MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
			stmt.accept(visitor);

			// 获取表名称
			// System.out.println("Tables : " + visitor.getTables());
			// 获取操作方法名称,依赖于表名称
			System.out.println("Manipulation : " + visitor.getTables());
			// 获取字段名称
			System.out.println("fields : " + visitor.getColumns());
		}

	}

}